/** 查找数组内相邻的数字 */
export const findAdjacentPairs = (arr) => {
	// 先对数组进行排序
	arr.sort((a, b) => a - b);
	let result = [];
	let temp = [];
	for (let i = 0; i < arr.length; i++) {
		if (i === 0 || arr[i] === arr[i - 1] + 1) {
			temp.push(arr[i]);
		} else {
			if (temp.length > 1) result.push(...temp);
			temp = [arr[i]];
		}
	}
	// 检查最后一组连续数字
	if (temp.length > 1) result.push(...temp);
	return result;
};

/** 查找数组内相邻数字并将相邻和不相邻的数字返回出来 */
export const separateAdjacentAndNonAdjacent = (arr) => {
	arr.sort((a, b) => a - b); // 先对数组进行排序

	let adjacent = [];
	let nonAdjacent = [];
	let temp = [arr[0]];

	for (let i = 1; i < arr.length; i++) {
		if (arr[i] === arr[i - 1] + 1) {
			temp.push(arr[i]);
		} else {
			if (temp.length > 1) {
				adjacent.push(...temp);
			} else {
				nonAdjacent.push(temp[0]);
			}
			temp = [arr[i]];
		}
	}

	// 处理最后一组
	if (temp.length > 1) {
		adjacent.push(...temp);
	} else {
		nonAdjacent.push(temp[0]);
	}

	// 去重
	adjacent = Array.from(new Set(adjacent));
	nonAdjacent = Array.from(new Set(nonAdjacent));

	return { adjacent, nonAdjacent };
};

/**
 * @description 牙位转换
 */
export const toothConversion = (data = []) => {
	if (data.length == 0) return;
	const toothMap = {
		18: 1,
		17: 2,
		16: 3,
		15: 4,
		14: 5,
		13: 6,
		12: 7,
		11: 8,
		21: 9,
		22: 10,
		23: 11,
		24: 12,
		25: 13,
		26: 14,
		27: 15,
		28: 16,
		48: 17,
		47: 18,
		46: 19,
		45: 20,
		44: 21,
		43: 22,
		42: 23,
		41: 24,
		31: 25,
		32: 26,
		33: 27,
		34: 28,
		35: 29,
		36: 30,
		37: 31,
		38: 32
	};
	return data
		.map((item) => toothMap[item])
		.filter(Boolean)
		.join(',');
};

/**
 * @description 格式化字节
 * @param {*} bytes
 * @returns
 */
export const formatBytes = (bytes) => {
	const KB = 1024;
	const MB = KB * 1024;
	const GB = MB * 1024;

	if (bytes >= GB) {
		return (bytes / GB).toFixed(2) + ' GB';
	} else if (bytes >= MB) {
		return (bytes / MB).toFixed(2) + ' MB';
	} else if (bytes >= KB) {
		return (bytes / KB).toFixed(2) + ' KB';
	} else {
		return bytes + ' bytes';
	}
};

/** 将相邻的数字处理成二维数组 */
export const groupConsecutiveNumbers = (arr) => {
	let result = [];
	let temp = [arr[0]];

	for (let i = 1; i < arr.length; i++) {
		if (arr[i] === arr[i - 1] + 1) {
			temp.push(arr[i]);
		} else {
			result.push(temp);
			temp = [arr[i]];
		}
	}

	// 最后一个区间添加到结果中
	result.push(temp);
	return result;
};

/**
 * @description  文件下载
 * @param {*} file
 * @param {*} fileName
 * @param {*} options
 */
export const fileDownload = async (url, filename) => {
	const response = await fetch(url);
	const blob = await response.blob();
	const objectUrl = URL.createObjectURL(blob);

	const a = document.createElement('a');
	a.href = objectUrl;
	a.download = filename || 'download.mp4'; // 默认文件名
	a.style.display = 'none';
	document.body.appendChild(a);
	a.click();

	// 清理资源
	window.URL.revokeObjectURL(objectUrl);
	document.body.removeChild(a);
};
